// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const TcbRouter = require('tcb-router')
const db = cloud.database()

const userCollection = db.collection('user')
const MAX_LIMIT = 100

// 云函数入口函数
exports.main = async (event, context) => {
  const app = new TcbRouter({ event })
  

  app.router('login', async (ctx) => {
    const wxContext = cloud.getWXContext()
    // 获取用户的详情
    const countResult = await userCollection.count()
    const total = countResult.total
    const batchTimes = Math.ceil(total / MAX_LIMIT)
    let tasks = []
    for (let i = 0; i < batchTimes; i++) {
      const promise = userCollection.skip(i * MAX_LIMIT).limit(MAX_LIMIT).get()
      tasks.push(promise)
    }
    let list = {
      data: []
    }
    if (tasks.length > 0) {
      list = (await Promise.all(tasks)).reduce((acc, cur) => {
        return {
          data: acc.data.concat(cur.data),
          errMsg: acc.errMsg,
        }
      })
    }
    const oneData = {
      openid: wxContext.OPENID,
      user: event.info
    }
    let methods = 'add'
    let bodyData = Object.assign({}, oneData)
    let newData = ''
    
    if (list.data.length > 0) {
      for (let i = 0, len = list.data.length; i < len; i++) {
        let flag = true
        if (list.data[i].openid === wxContext.OPENID) {
          if (list.data[i].user) {
            bodyData.user = list.data[i].user
            flag = false
            newData = ''
          } else if (event.info) {
            bodyData.user = event.info
            flag = true
            newData = oneData
            methods = 'update'
          }
          break
        }
        if (flag) {
          newData = oneData
        }
      }
    } else {
      newData = oneData
    }

    if (newData) {
      if (methods === 'add') {
        await userCollection.add({
          data: {
            ...oneData,
            createTime: db.serverDate()
          }
        }).then(res => {
          console.log('插入成功')
        }).catch(err => {
          console.log('插入失败', err)
        })
      } else if (methods === 'update') {
        await userCollection.where({
          openid: wxContext.OPENID
        }).update({
          data: {
            user: oneData.user,
            updateTime: db.serverDate()
          }
        }).then(res => {
          console.log('更新成功')
        }).catch(err => {
          console.log('更新失败', err)
        })
      }
      
    }

    ctx.body = {
      ...bodyData
    }
  })
  
  return app.serve()
}